package com.example.mongo.config;

import com.example.mongo.config.props.MultipleMongoProperties;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.internal.MongoClientImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
public class MultipleMongoConfig {

    @Autowired
    private MultipleMongoProperties mongoProperties;

    /**
     * 补充说明:如果使用了@Primary,其他@Autowired注入时idea不会检查bean名是否一致,默认注入该bean
     * 如果使用的bean会被其他地方自动装配调用,就必须加@Primaryeg:MongoTemplate 会被 MongoDbFactoryDependentConfiguration使用到,此时需要告诉spring使用哪一个
     * 如果自己代码里想指定注入某个bean名可以使用@Resource或者@Autowired+@Qualifier
     * @return
     */
    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate primaryMongoTemplate(){
        return new MongoTemplate(this.mongoDbFactory(mongoProperties.getPrimary()));
    }

    /**
     * @Qualifier 可以用来声明注入的bean名称
     * @return
     */
    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate secondaryMongoTemplate(){
        return new MongoTemplate(this.mongoDbFactory(mongoProperties.getSecondary()));
    }
    
    private MongoDbFactory mongoDbFactory(MongoProperties mongoProperties){
        MongoClient mongoClient = MongoClients.create(mongoProperties.getUri());
        return new SimpleMongoClientDbFactory(mongoClient, mongoProperties.getDatabase());
    }
}
